package main

import (
	"fmt"
)

type ProcessData struct {
	arriveTime int     // 到达时间
	workTime   int     // 工作时间
	finishTime int     // 完成时间
	turnTime   int     // 周转时间
	powerTime  float64 // 带权周转时间
}

var (
	currentTime = 0 // 当前时间
)

func main() {
	var processList []ProcessData
	processList = append(processList, ProcessData{
		arriveTime: 5,
		workTime:   2,
	})
	processList = append(processList, ProcessData{
		arriveTime: 0,
		workTime:   10,
	})
	processList = append(processList, ProcessData{
		arriveTime: 3,
		workTime:   4,
	})
	processList = append(processList, ProcessData{
		arriveTime: 1,
		workTime:   3,
	})
	// 按到达时间排序
	processList = sortProcess(processList)
	for i := range processList {
		if currentTime < processList[i].arriveTime {
			currentTime = processList[i].arriveTime
		}
		currentTime += processList[i].workTime
		processList[i].finishTime = currentTime
		processList[i].turnTime = processList[i].finishTime - processList[i].arriveTime
		processList[i].powerTime = float64(processList[i].turnTime) / float64(processList[i].workTime)
	}
	display(processList)
}

// 快速排序
func sortProcess(processList []ProcessData) []ProcessData {
	if len(processList) <= 1 {
		return processList
	}
	var smaller []ProcessData
	var bigger []ProcessData
	current := processList[0]
	other := processList[1:]
	for _, p := range other {
		if p.arriveTime < current.arriveTime {
			smaller = append(smaller, p)
		} else {
			bigger = append(bigger, p)
		}
	}
	result := append(sortProcess(smaller), current)
	result = append(result, sortProcess(bigger)...)
	return result
}

// 显示列表数据
func display(processList []ProcessData) {
	var totalTurn float64
	var totalPower float64
	for _, p := range processList {
		totalTurn += float64(p.turnTime)
		totalPower += p.powerTime
		fmt.Printf("到达时间: %-3d 工作时间: %-3d 完成时间: %-3d 周转时间: %-3d 带权周转时间: %-3.2f\n",
			p.arriveTime,
			p.workTime,
			p.finishTime,
			p.turnTime,
			p.powerTime)
	}
	length := len(processList)
	fmt.Println("平均周转时间:", float64(totalTurn)/float64(length))
	fmt.Println("平均带权周转时间:", totalPower/float64(length))
}
